import $ from "@jquery";
import { onDocumentComplete, watchElement } from "@utils";

function handleFix(target) {
  $(target).autoFixDirection();

  //修正pre 便签内的内容direction
  $(target)
    .find("pre")
    .css("direction", "ltr")
    .css("font-family", "uighurFont");

  //修复blockquote border-left
  $("blockquote").each(function () {
    console.log($(this), $(this).isRTL(), $(this).css("border-left"));
    if ($(this).isRTL()) {
      //left换成right
      $(this).css("border-right", "3px solid #eee");
      $(this).css("padding-right", "1em");
      $(this).find("li").css("margin-right", "23px");

      $(this).children("ul").css("margin-right", "3px");
      $(this).css("border-left", "0px");
      $(this).css("padding-left", "0px");
      $(this).find("li").css("margin-left", "0px");
    }
  });
}

/**
 *对当前document做额外的处理
 * @param {Function} cb
 */
export function handleYuque(cb) {
  onDocumentComplete(document, function () {
    //第一次
    handleFix($(document).find("body"));
    cb(document);

    //body发生改变后的每一次
    watchElement(
      document.body,
      {
        childList: true,
        subtree: true,
      },
      function (mutationsList) {
        for (let mutation of mutationsList) {
          mutation && handleFix($(mutation.target));
        }
      }
    );
  });
}
